import React, { Component } from 'react'
import {
  View, Text, StyleSheet, KeyboardAvoidingView, Platform,
  ScrollView, TouchableOpacity, Keyboard, DeviceEventEmitter
} from 'react-native'
import DateTimePicker from "react-native-modal-datetime-picker"
import Picker from 'react-native-picker'

import NavBar from 'src/components/navBar'
import Divider from 'src/components/Divider'
import Layer from "src/components/Layer"
import navigationhelper from 'src/components/navigationhelper'
import NameInput, { InputTypes } from 'src/components/Input/NameInput'

import { inject } from "mobx-react/native"
import { getBankId, getPovinceAndCityId, transformCardData } from 'src/util'
import ImagePicker from "react-native-image-crop-picker"
import { uploadCardImage } from "src/service/Auth"
import ActionSheet from "react-native-actionsheet"

const countDownInitState = {
  countDown: 60,
  countText: '获取验证码',
  countColor: '#378efb',
  isCountDown: false
}

const days = []
for (let i = 1; i < 32; i++) {
  if (i < 10) {
    days.push('0' + i.toString())
  } else {
    days.push(i.toString())
  }
}


@inject('userAuth', 'cardManager')
export default class AddCardView extends Component {

  constructor(props) {
    super(props)
    this.mounted = false
    this.countDownInterval = null
    this.state = {
      ...countDownInitState,
      isShowDatePicker: false,
      area: ['', ''],
      bank: [''],
      validityDate: '',
      paymentDate: [''],
      repaymentDate: [''],
      datePickerValue: new Date()
    }
  }

  componentDidMount() {
    if (this.props.cardManager.areaData.length === 0) {
      this.props.cardManager.fetchArea()
    }
    if (this.props.cardManager.banks.length === 0) {
      this.props.cardManager.fetchBanks()
    }
    this.mounted = true
  }

  componentWillUnmount() {
    this.mounted = false
  }

  handleStartCountDownTimer = () => {
    //获取验证码
    this.props.userAuth.getSmsCode({
      mobile: this.state.mobile
    }).then(() => {
      this.countDownInterval && clearInterval(this.countDownInterval)
      this.setState({ ...countDownInitState })
      this.countDownInterval = setInterval(this.handleCountDownTimer, 1000)
    })
  }

  handleCountDownTimer = () => {
    let { countDown } = this.state
    if (countDown === 1) {
      this.countDownInterval && clearInterval(this.countDownInterval)
      this.setState({ ...countDownInitState })
    } else {
      countDown--
      this.setState({
        countDown,
        countText: '倒计时' + countDown + 's',
        countColor: '#8e8e93',
        isCountDown: true
      })
    }
  }

  handleShowDatePicker = (key) => () => {
    Picker.hide()
    Keyboard.dismiss()
    this.dateKey = key
    let { datePickerValue } = this.state
    if (this.state[key]) {
      datePickerValue = new Date(this.state[key])
    } else {
      datePickerValue = new Date()
    }
    this.setState({ isShowDatePicker: true, datePickerValue })
  }

  handleShowDays = (key) => () => {
    Keyboard.dismiss()
    let payload = {
      pickerData: days,
      pickerConfirmBtnColor: [55, 142, 251, 1],
      pickerCancelBtnColor: [55, 142, 251, 1],
      pickerBg: [255, 255, 255, 1],
      selectedValue: this.state[key],
      pickerTitleText: '选择日期',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      onPickerConfirm: data => {
        let item = {}
        item[key] = data
        this.setState(item)
      }
    }
    Picker.init(payload)
    Picker.show()
  }

  handleHideDatePicker = () => {
    this.dateKey = undefined
    this.setState({ isShowDatePicker: false })
  }

  handleShowBankPicker = () => {
    Keyboard.dismiss()
    let payload = {
      pickerConfirmBtnColor: [55, 142, 251, 1],
      pickerCancelBtnColor: [55, 142, 251, 1],
      pickerData: this.props.cardManager.banksPureData,
      selectedValue: this.state.bank,
      pickerBg: [255, 255, 255, 1],
      pickerTitleText: '选择开户行',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      onPickerConfirm: data => {
        this.setState({ bank: data })
      }
    }
    Picker.init(payload)
    Picker.show()
  }

  data = [
    ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
    ['2019', '2020', '2021', '2022', '2023', '2024', '2025', '2026', '2027', '2028', '2029', '2030', '2031',
      '2032', '2033', '2034', '2035', '2036', '2037', '2038']
  ]
  handleShowYearAndMonth = () => {
    Keyboard.dismiss()
    let payload = {
      pickerConfirmBtnColor: [55, 142, 251, 1],
      pickerCancelBtnColor: [55, 142, 251, 1],
      pickerBg: [255, 255, 255, 1],
      pickerData: this.data,
      selectedValue: this.state.area,
      pickerTitleText: '选择年月',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      onPickerConfirm: data => {
        let str1 = data[0]
        let str2 = data[1]
        let str3 = str2.substring(2, 4)
        let str4 = `${str1 + '/' + str3}`
        this.setState({ validityDate: str4 })
      }
    }
    Picker.init(payload)
    Picker.show()
  }

  handleShowAreaPicker = () => {
    Keyboard.dismiss()
    let payload = {
      pickerConfirmBtnColor: [55, 142, 251, 1],
      pickerCancelBtnColor: [55, 142, 251, 1],
      pickerBg: [255, 255, 255, 1],
      pickerData: this.props.cardManager.areaPureData,
      selectedValue: this.state.area,
      pickerTitleText: '选择省市',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnText: '确定',
      onPickerConfirm: data => {
        this.setState({ area: data })
      }
    }
    Picker.init(payload)
    Picker.show()
  }

  handImageUpload = () => {
    this.ActionSheet.show()
  }

  handleDatePicked = (date) => {
    let data = { isShowDatePicker: false }
    if (this.dateKey) {
      data[this.dateKey] = date
    }
    this.setState({ ...data })

  }

  handleChangeText = (key) => (value) => {
    if (this.state[key] === value) return
    this.setState({ [key]: value })
  }

  handleAddNewCard = () => {
    Keyboard.dismiss()
    let { cardManager } = this.props
    let {
      card_number, bank, area, cvn2, amount, validityDate,
      paymentDate, repaymentDate, mobile, verifyCode
    } = this.state

    let bankId = getBankId(cardManager.banks, bank)
    let areaIds = getPovinceAndCityId(cardManager.areaData, area)

    Layer.showLoading()
   if (card_number.length < 15) {
      return Layer.showMsg('请输入正确的信用卡号')
    } 
    else if (!bankId) {
      return Layer.showMsg('请选择发卡行')
    } else if (!areaIds[0] || !areaIds[1]) {
      return Layer.showMsg('请输入发卡行所在省市')
    } else if (!cvn2) {
      return Layer.showMsg('请输入信用卡背面后三位安全码')
    } else if (!amount) {
      return Layer.showMsg('请输入信用卡额度')
    } else if (!validityDate) {
      return Layer.showMsg('请选择信用卡有效期')
    } else if (!paymentDate) {
      return Layer.showMsg('请选择账单日')
    } else if (!repaymentDate) {
      return Layer.showMsg('请选择还款日')
    } else if (!mobile) {
      return Layer.showMsg('请输入银行卡预留手机号码')
    }
    // else if (!verifyCode) {
    //   return Layer.showMsg('请输入短信验证码')
    // }
    this.props.cardManager.addCreditCard({
      bank_id: bankId,
      bank_card: card_number,
      valid_date: validityDate,
      cvv2: cvn2,
      statement_date: paymentDate[0],
      repayment_date: repaymentDate[0],
      quota: this.state.amount,
      province: areaIds[0],
      city: areaIds[1],
      mobile: mobile,
      token: this.props.userAuth.token,
      type: '02',
      // validate_code: verifyCode
    }).then((res) => {
      Layer.hiddenLoading()
      // navigationhelper.goBack()
      DeviceEventEmitter.emit('refreshCardManager')
      navigationhelper.navigate('AddCardSuccessView', { data: res.data })
    }).catch((error) => {
      Layer.hiddenLoading()
      Layer.showMsg(error.message)
    })
  }

  renderGetVerifyCodeView = () => {
    let { isCountDown, countText, countColor } = this.state
    if (isCountDown) {
      return (
        <Text style={[styles.countDownStyle, { color: countColor }]}>
          {countText}
        </Text>
      )
    }
    return (
      <TouchableOpacity onPress={this.handleStartCountDownTimer}>
        <Text style={[styles.countDownStyle, { color: countColor }]}>
          {countText}
        </Text>
      </TouchableOpacity>
    )
  }

  render() {
    let { area } = this.state
    let areaValue = ''
    if (area[0] && area[1]) {
      areaValue = area[0] + ' ' + area[1]
    }
    return (
      <KeyboardAvoidingView
        style={styles.container}
        behavior={Platform.OS === 'ios' ? 'padding' : 'none'}>
        <NavBar
          back={() => {
            Picker.hide()
            navigationhelper.goBack()
          }}
          title={'添加信用卡'}
          leftText={'返回'}
          barStyle={'dark-content'}
        />
        <ScrollView
          bounces={false}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps={'handled'}>
          <View style={{ height: 16 }} />
          <View style={styles.contentContainer}>
            <NameInput
              showLeftText
              hideClearImage
              editable={false}
              text={this.props.userAuth.currentUser.real_name}
              leftText={'真实姓名'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入真实姓名'}
              callback={this.handleChangeText('realName')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              hideClearImage
              editable={false}
              text={this.props.userAuth.currentUser.idcard}
              leftText={'身份证号'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入身份证号'}
              callback={this.handleChangeText('idNumber')} />
          </View>
          <View style={{ height: 12 }} />
          <View style={styles.contentContainer}>
            <NameInput
              showLeftText
              leftText={'信用卡号'}
              hideClearImage
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入信用卡号'}
              text={this.state.card_number}
              maxLength={16}
              keyboardType={'numeric'}
              showRightImage
              rightImage={require('src/assets/mine/cameraSmall.png')}
              rightImageEvent={this.handImageUpload}
              callback={this.handleChangeText('card_number')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              editable={false}
              text={this.state.bank && this.state.bank[0] || '请选择发卡行'}
              leftText={'开户行'}
              leftTextStyle={styles.leftTextStyle}
              isUseLabelPlaceholder={!(this.state.bank && this.state.bank[0])}
              placeholder={'请选择发卡行'}
              hideClearImage
              showRightImage
              rightImage={require('src/assets/icon_arrow_grey.png')}
              onPress={this.handleShowBankPicker} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              editable={false}
              isUseLabelPlaceholder={!areaValue}
              text={areaValue || '请选择发卡行所在省市'}
              leftText={'开户省市'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请选择发卡行所在省市'}
              hideClearImage
              showRightImage
              rightImage={require('src/assets/icon_arrow_grey.png')}
              onPress={this.handleShowAreaPicker} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              editable={false}
              isUseLabelPlaceholder={!this.state.validityDate}
              text={this.state.validityDate || '请选择信用卡有效期'}
              leftText={'有效期'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请选择信用卡有效期'}
              hideClearImage
              showRightImage
              rightImage={require('src/assets/icon_arrow_grey.png')}
              onPress={
                this.handleShowYearAndMonth
                // this.handleShowDatePicker('validityDate')
              } />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              leftText={'CVN2'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入信用卡背面后三位安全码'}
              maxLength={3}
              keyboardType={'numeric'}
              callback={this.handleChangeText('cvn2')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              editable={false}
              leftText={'账单日'}
              isUseLabelPlaceholder={!this.state.paymentDate[0]}
              text={this.state.paymentDate[0] || '请选择账单日'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请选择账单日'}
              hideClearImage
              showRightImage
              rightImage={require('src/assets/icon_arrow_grey.png')}
              onPress={this.handleShowDays('paymentDate')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              editable={false}
              leftText={'还款日'}
              isUseLabelPlaceholder={!this.state.repaymentDate[0]}
              text={this.state.repaymentDate[0] || '请选择还款日'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请选择还款日'}
              hideClearImage
              showRightImage
              rightImage={require('src/assets/icon_arrow_grey.png')}
              onPress={this.handleShowDays('repaymentDate')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              leftText={'额度'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入信用卡额度'}
              maxLength={7}
              keyboardType={'numeric'}
              callback={this.handleChangeText('amount')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              leftText={'手机号码'}
              maxLength={11}
              keyboardType={'numeric'}
              inputType={InputTypes.PHONE}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入银行卡预留手机号码'}
              callback={this.handleChangeText('mobile')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
          </View>
          <TouchableOpacity
            style={styles.addBtnContainer}
            onPress={this.handleAddNewCard}>
            <Text style={styles.addBtnText}>{'添加'}</Text>
          </TouchableOpacity>
          <View style={{ height: 16 }} />
        </ScrollView>
        <DateTimePicker
          locale='zh-Hans'
          titleIOS={'选择时间'}
          cancelTextIOS={'取消'}
          confirmTextIOS={'确定'}
          date={this.state.datePickerValue}
          isVisible={this.state.isShowDatePicker}
          onConfirm={this.handleDatePicked}
          onCancel={this.handleHideDatePicker}
        />
        <ActionSheet
          ref={o => this.ActionSheet = o}
          options={['拍照', '从手机相册选择', '取消']}
          cancelButtonIndex={2}
          onPress={(index) => {
            var promise = undefined
            if (index === 0) {
              promise = ImagePicker.openCamera({
                width: 300,
                height: 400,
                compressImageQuality: 0.5,
                cropping: true,
              })
            } else if (index === 1) {
              promise = ImagePicker.openPicker({
                width: 300,
                height: 400,
                compressImageQuality: 0.5,
                cropping: true
              })
            }
            if (promise) {
              promise.then(image => {
                Layer.showMsg('开始上传')
                uploadCardImage({
                  image: image,
                  token: this.props.userAuth.token,
                }).then((res) => {
                  var bank_id = res.data.bank_id
                  var backName = ''
                  this.props.cardManager.banks.forEach(function (item) {
                    if (item.id === bank_id) {
                      backName = item.name
                    }
                  })
                  // var validityDate = transformCardData(res.data.valid_date)

                  this.setState({
                    card_number: res.data.bank_card_number,
                    bank: [backName]
                  })
                })
              })
            }
          }}
        />
      </KeyboardAvoidingView>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5'
  },
  contentContainer: {
    backgroundColor: 'white'
  },
  leftTextStyle: {
    width: 70,
    marginLeft: 16
  },
  countDownStyle: {
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 15
  },
  addBtnContainer: {
    height: 50,
    marginLeft: 16,
    marginRight: 16,
    marginTop: 25,
    borderRadius: 5,
    backgroundColor: '#ff2121',
    alignItems: 'center',
    justifyContent: 'center'
  },
  addBtnText: {
    fontSize: 16,
    color: 'white',
    fontWeight: 'bold'
  }
})